package com.xhu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xhu.common.request.PredictRequest;
import com.xhu.exceptions.SalePredictionException;
import com.xhu.handler.SalePredictionResultHandler;
import com.xhu.mapper.SalePredictionMapper;
import com.xhu.pojo.SalePrediction;
import com.xhu.service.SalePredictionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;

@Service
public class SalePredictionServiceImpl extends ServiceImpl<SalePredictionMapper, SalePrediction>
        implements SalePredictionService {

    @Autowired
    SalePredictionMapper mapper;

    /**
     * 结果生成处理器
     */
    @Autowired
    SalePredictionResultHandler handler;

    @Override
    public IPage<SalePrediction> getAllPrediction(Integer current, Integer size) {
        return this.page(new Page<>(current, size));
    }

    @Override
    public void predict(PredictRequest request, File file) {
        //校验，更完整的校验在handler内
        if (request == null) {
            throw new SalePredictionException("预测信息为空");
        }
        if (file == null) {
            throw new SalePredictionException("文件为空或读取失败");
        }

        //得到结果
        String predictResult = handler.predict(request, file);

        //将预测结果填入
        SalePrediction entity = new SalePrediction();
        entity.setSalResult(predictResult)
                .setSalPredMonth(request.getTime())
                .setSalPredTitle(request.getTitle())
                .setSalDepartment(request.getDepartment())
                .setSalPredOperator(request.getOperator());
        entity.setUpdateTime(null);
        entity.setSalPredId(null);
        //写入数据库
        this.save(entity);

    }

    @Override
    public IPage<SalePrediction> getByDateTime(String time, Integer page, Integer size){
        LambdaQueryWrapper<SalePrediction> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(SalePrediction::getSalPredMonth, time);
        return this.page(new Page<>(page, size), wrapper);
    }

}
